package club.kingyin.easycache.component;

import club.kingyin.easycache.cache.AbstractCache;
import club.kingyin.easycache.exception.InvokeException;
import club.kingyin.easycache.method.CacheMethod;
import lombok.extern.slf4j.Slf4j;

// 异常拦截器
@Slf4j
public abstract class ExceptionCacheHandler implements CachePostProcess {
    @Override
    public boolean postProcessPreSetCache(CacheMethod invocation, Object value, Timer timer) {
        // 如果是异常则执行异常处理器
        if (value instanceof InvokeException) {
            InvokeException invokeException = (InvokeException) value;
            return filter(invocation,invokeException);
        }
        return true;
    }

    protected abstract boolean filter(CacheMethod invocation, InvokeException e);

    @Override
    public Object postProcessAfterSetCache(CacheMethod invocation, Object value, AbstractCache cache) {
        // 如果是异常则执行转换器
        if (value instanceof InvokeException) {
            log.warn("方法：[{}] 异常监测 {}", invocation.getMethod().getName(), value);
            return unusualResultConversion(invocation, (InvokeException) value);
        }
        return value;
    }

    @Override
    public void postProcessBeforeSetCache(CacheMethod invocation, Object value, Timer timer) {
        // 不做任何处理
    }

    protected abstract Object unusualResultConversion(CacheMethod invocation, InvokeException e);
}
